<?php 
cs()->registerCssFile('/sites/1/kodo/kodostudios/themes/kodo-cms/styles/form.css');
?>
<div class="form">
<form action="" method="post">
    <div class="row">
        <label>Token</label>
        <input name="ApiSec[token]" size="50" value="<?php echo Yii::app()->session->get(ApiSec::TOKEN_KEY_IN_SESSION) ?>" />
    </div>
    <div class="row">
        <label>Service ID</label>
        <input name="SID" size="50" value="Core.WebApi.getToken" />
    </div>
    <div class="row">
        <label>Params</label>
    </div>
    <div class="row param">
        <input name="key">
        <input name="value" size="80">
        <input type="hidden" name="param">
        <a href="#" class="add">Add</a>
        <a href="#" class="remove">Remove</a>
    </div>
    <input type="hidden" name="ApiSec[t]"> 
    <input type="hidden" name="ApiSec[hash]"> 
    <div class="row">
        <input type="submit" value="Submit">
    </div>
</form>
</div>

<script>
var prepared = false;
$('form').submit(function(){
    if (!prepared){
        date = new Date();
        $('input[name="ApiSec[t]"]').val(Math.floor(date.getTime()/1000));
        
        $.ajax({
            url: '<?php echo url('/testApi/prepare') ?>',
            data: {
                token: $('input[name="ApiSec[token]"]').val(),
                t: $('input[name="ApiSec[t]"]').val(),
            },
            success: function(data){
                prepared = true;
                eval('data='+data); 
                // set hash and t params
                $('input[name="ApiSec[hash]"]').val(data.hash);
                
                // build other params
                $('div.param').each(function(){
                    name = $(this).find('input[name="key"]').val();$(this).find('input[name="key"]').remove();
                    value = $(this).find('input[name="value"]').val();$(this).find('input[name="value"]').remove();
                    param = $(this).find('input[name=param]');
                    param.val(value);
                    param.attr('name',name);
                })
                
                $('form').attr('action','<?php echo url('/Core/service/index', array('FORMAT' => 'xml')) ?>&SID='+$('input[name=SID]').val());
                $('form').get(0).submit();
            },
            asyns: true,
            type: 'post'
        })
    }
    return false;
})

$(document).ready(function(){
    $('a.add').click(function(){
        parent = $(this).parent();
        parent.after(parent.clone());
    })
    $('a.remove').click(function(){
        $(this).parent().remove();
    })
})
</script>